package dao

import (
	"context"
	"gitee.com/chunanyong/zorm"
	"gitee.com/xinshortlink/internal/constants"
	"gitee.com/xinshortlink/internal/dal/db/model"
	"gitee.com/xinshortlink/internal/dto/resp/bizerr"
	"go.uber.org/zap"
	"time"
)

type GroupDao struct {
	logger *zap.Logger
}

func NewGroupDao(logger *zap.Logger) *GroupDao {
	return &GroupDao{logger: logger}
}

func (dao *GroupDao) Create(ctx context.Context, g *model.GroupStruct) error {
	g.CreateTime = time.Now()

	_, err := zorm.Insert(ctx, g)
	if err != nil {
		return bizerr.New(bizerr.DB, "创建分组出错", err)
	}

	return nil
}

func (dao *GroupDao) Update(ctx context.Context, g *model.GroupStruct) error {
	g.CreateTime = time.Now()
	_, err := zorm.UpdateNotZeroValue(ctx, g)
	if err != nil {
		return bizerr.New(bizerr.DB, "更新分组出错", err)
	}

	return nil
}

func (dao *GroupDao) Delete(ctx context.Context, g *model.GroupStruct) error {
	g.DelTime = time.Now()
	g.DelState = constants.YES
	_, err := zorm.UpdateNotZeroValue(ctx, g)
	if err != nil {
		return bizerr.New(bizerr.DB, "删除分组出错", err)
	}

	return nil
}

func (dao *GroupDao) FindGroupById(ctx context.Context, id int64) (*model.GroupStruct, error) {
	finder := zorm.NewSelectFinder(model.GroupStructTableName).Append("WHERE id = ?", id)

	g := &model.GroupStruct{}
	has, err := zorm.QueryRow(ctx, finder, g)
	if err != nil {
		return nil, bizerr.New(bizerr.DB, "查询分组出错", err)
	}

	if !has {
		return nil, nil
	}

	return g, nil
}

func (dao *GroupDao) FindGroupByAccountName(ctx context.Context, accountName string) ([]*model.GroupStruct, error) {
	finder := zorm.NewSelectFinder(model.GroupStructTableName).Append("WHERE account_name = ? AND del_state = ?", accountName, constants.NO)

	list := make([]*model.GroupStruct, 0)
	err := zorm.Query(ctx, finder, &list, nil)

	if err != nil {
		return nil, bizerr.New(bizerr.DB, "查询分组出错", err)
	}

	return list, err
}

func (dao *GroupDao) FindGroupCountByAccountName(ctx context.Context, accountName string) (int, error) {
	finder := zorm.NewSelectFinder(model.GroupStructTableName, "count(id)").Append("WHERE account_name = ? AND del_state = ?", accountName, constants.NO)

	var count int

	_, err := zorm.QueryRow(ctx, finder, &count)
	if err != nil {
		return 0, bizerr.New(bizerr.DB, "查询分组出错", err)
	}

	return 0, err
}
